// mobile bind
// ============

define(['zepto', 'utils', 'JST', 'countDown'], function($, utils, JST){
  return {
    init: function(_CTX_) {
      this._CTX_ = _CTX_
      this.$bindButton = $('[href="#mobile-bind"]')
      this.$bindButton.length ? this.bindMobileBindingAction() : void 0
    },

    /**
     * Bind action fired on clicking mobile binding button
     */
    bindMobileBindingAction: function() {
      var that = this

      // On binding mobile
      this.$bindButton.on('click', function(e) {
        e.preventDefault()
        var $page = that.compileMobileBindingPage()
        $.push.transitionIn($page)
      })

      // On mobile binded
      this.$bindButton.on('binded:profile:mobile', function(e, $page, mobile) {
        // Transition out mobile page
        var itemDomString = $(JST.mobileItemTpl({ 'mobile': mobile }))
        $.push.transitionOut($page, {
          beforeTransition: function() {
            that.$bindButton.off()
              .parent().empty().html(itemDomString)
          }
        })
      })
    },

    /**
     * Compile mobile binding page and return jQuery object
     */
    compileMobileBindingPage: function() {
      var $page = $(JST.mobileBindTpl())
      this.bindMobileBindingPageEvent($page)
      return $page
    },

    /**
     * Bind mobile binding page event
     */
    bindMobileBindingPageEvent: function($page) {
      var that = this,
        $mobile = $('input[name="mobile"]', $page),
        $code = $('input[name="code"]', $page)

      // On requesting verify code
      $page.on('click', '#get-code', function(e) {
        e.preventDefault()

        var $button = $(e.currentTarget), mobile = $mobile.val().trim()
        if (that.isMobile(mobile)) {
          // Disable button
          $button.css('pointer-events', 'none')
          // Request verifiy code
          that.requestVerifyCode(mobile, function() {
            $button.countdown('s后重试', 60, function() {
              $button.css('pointer-events', 'initial').text('获取验证码')
            })
          }, function() {
            $button.css('pointer-events', 'initial')
          })
        } else {
          $.toast('请输入正确的手机号码')
        }
      })

      // On submiting mobile
      $page.on('click', '#submit', function(e) {
        e.preventDefault()

        var mobile = $mobile.val().trim(), code = $code.val().trim()
        if (!that.isMobile(mobile)) return $.toast('请输入正确的手机号码')
        if (!code) return $.toast('验证码不能为空')

        var submiting = that.submitMobile(mobile, code)
        $.when(submiting).done(function(data) {
          that.$bindButton.trigger('binded:profile:mobile', [$page, data.mobile])
        })
      })
    },

    /**
     * Check mobile value is valid or not
     */
    isMobile: function(mobile) {
      return mobile && /^((13)|(15)|(17)|(18))\d{9}$/.test(mobile)
    },

    /**
     * Request server to send verifiy code to mobile
     */
    requestVerifyCode: function(mobile, success, failure) {
      $.showIndicator()
      utils.requestVerifyCode(mobile, function() {
        $.hideIndicator()
        $.toast('验证码发送成功')
        success && success()
      }, failure)
    },

    /**
     * Submit mobile and code for binding
     */
    submitMobile: function(mobile, code) {
      var that = this, defer = $.Deferred()
      $.showIndicator()
      $.post(that._CTX_.root + '/bind-mobile', { 'mobile': mobile, 'code': code })
        .done(function(response) {
          $.hideIndicator()
          utils.processResult(response, function(result) {
            defer.resolve(result.data)
          }, function(result) {
            $.toast(result.message || '绑定失败')
          })
        })

      return defer.promise()
    }
  }

})

